package com.hmall.item.web;


import com.hmall.common.dto.PageDTO;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import com.hmall.item.service.ItemTCCService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.item.mapper.ItemMapper;



@RestController
@RequestMapping("/item")
public class ItemController {
    @Autowired
    private IItemService itemService;

    @Autowired
    private ItemTCCService tccService;

    @Autowired
    private ItemMapper itemMapper;

    /**
     * 事务扣减库存
     * @param itemId
     * @param num
     */
    @PutMapping("/stock/{itemId}/{num}")
    public void deduct(@PathVariable Long itemId,@PathVariable Integer num){
        tccService.deduct(itemId,num);
    }

    @PutMapping("/refund/stock")
    void refundItemStock(@RequestBody Map<String,Object> map) {
        Long itemId = Long.parseLong(String.valueOf(map.get("itemId")));
        Integer num = Integer.parseInt(String.valueOf(map.get("num")));
        itemService.refundItemStock(itemId,num);
    }
    //上架,下架商品
    @PutMapping("/status/{id}/{status}")
    public void enableAndDisableItem(@PathVariable Long id, @PathVariable Integer status){
        itemService.enableAndDisableItem(id,status);
    }


    //修改商品
    @PutMapping
    public void updateItem(@RequestBody Item item){

        itemService.updateItem(item);
    }

    //根据ID删除商品
    @DeleteMapping("/{id}")
    public void deleteItem(@PathVariable Integer id) {
        itemService.deleteItem(id);
    }


    /**
     * 分页查询
     * @return
     */
    @GetMapping("/list")
    public PageDTO<Item> pageList(@RequestParam("page") Long page, @RequestParam("size") Long size) {
        return itemService.pageList(page, size);
    }

    /**
     * 根据id查询商品
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Item getItemById(@PathVariable Long id) {
        return itemService.getByItemId(id);
    }

    @PostMapping
    public String addProduct(@RequestBody Item Item) {
        int result = itemService.addItem(Item);
        if (result > 0) {
            return "商品新增成功";
        } else {
            return "商品新增失败";
        }
    }
}

